/**
 * 
 */
package org.mspring.mlog.web.module.web.ucenter.admin;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mspring.mlog.entity.Attachment;
import org.mspring.mlog.entity.Twitter;
import org.mspring.mlog.entity.TwitterReply;
import org.mspring.mlog.entity.security.User;
import org.mspring.mlog.service.AttachmentService;
import org.mspring.mlog.service.TwitterReplyService;
import org.mspring.mlog.service.TwitterService;
import org.mspring.mlog.web.query.TwitterQueryCriterion;
import org.mspring.mlog.web.security.SecurityUtils;
import org.mspring.platform.dao.support.Page;
import org.mspring.platform.dao.support.Sort;
import org.mspring.platform.utils.RequestUtils;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.web.ResponseEntity;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Liu Jun
 * @since 2013-06-22
 * @description
 * @TODO
 */
@Widget
@RequestMapping({ "/u/{username}/admin/twitter", "/u/{username}/admin/t" })
public class UCenterAdmin_TwitterWidget extends Abstract_UCenterAdminWidget {

    @Autowired
    private TwitterService twitterService;
    @Autowired
    private TwitterReplyService twitterReplyService;
    @Autowired
    private AttachmentService attachmentService;

    /**
     * 微博列表
     * 
     * @param id
     * @param request
     * @param response
     * @return
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @RequestMapping("/list")
    public String list(@ModelAttribute Page<Twitter> twitterPage, @ModelAttribute Twitter twitter, @RequestParam Map queryParams, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (spaceUser == null) {
            return "skin:/errors/404";
        }
        if (twitterPage == null) {
            twitterPage = new Page<Twitter>();
        }
        twitterPage.setSort(new Sort("id", Sort.DESC));

        if (twitter == null) {
            twitter = new Twitter();
        }

        queryParams.put("author.id", spaceUser.getId());
        twitterPage = twitterService.listPage(new TwitterQueryCriterion(queryParams), twitterPage);
        model.addAttribute("twitterPage", twitterPage);
        return "skin:/ucenter/admin/twitter/list";
    }

    /**
     * 后台添加微博
     * 
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public ResponseEntity add(@RequestParam(required = false) String content, @RequestParam(required = false) Long attachment, HttpServletRequest request, HttpServletResponse response, Model model) {
        ResponseEntity rsp = new ResponseEntity();
        User user = SecurityUtils.getCurrentUser(request);
        if (user == null) {
            rsp.setSuccess(false);
            rsp.setMessage("请先登录");
            return rsp;
        }
        if (!user.getId().equals(spaceUser.getId())) {
            rsp.setSuccess(false);
            rsp.setMessage("无权操作");
            return rsp;
        }
        if (StringUtils.isBlank(content)) {
            rsp.setSuccess(false);
            rsp.setMessage("请输入要发表的内容");
            return rsp;
        }

        try {
            Twitter twitter = new Twitter();
            twitter.setAuthor(user);
            twitter.setContent(content);
            twitter.setIp(RequestUtils.getRemoteIP(request));
            if (attachment != null) {
                twitter.setImage(new Attachment(attachment));
            }
            twitter.setCreateTime(new Date());
            twitter = twitterService.save(twitter);

            // 绑定图片和twitter
            if (attachment != null) {
                attachmentService.setAttachmentFkey(attachment, Attachment.AttachFromType.FROM_TWITTER, twitter.getId().toString());
            }

            if (twitter.getImage() != null && twitter.getImage().getId() != null && StringUtils.isBlank(twitter.getImage().getPath())) {
                Attachment image = attachmentService.get(twitter.getImage().getId());
                twitter.setImage(image);
            }

            rsp.setSuccess(true);
            rsp.setMessage("发表成功");
            rsp.put("twitter", twitter);
            return rsp;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            rsp.setSuccess(false);
            rsp.setMessage("发表内容失败");
            return rsp;
        }
    }

    /**
     * 删除微博
     * 
     * @param id
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseEntity deleteTwitter(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Long id = RequestUtils.getRequestParameterAsLong(request, "id");
        ResponseEntity rsp = new ResponseEntity();
        if (id == null) {
            rsp.setSuccess(false);
            rsp.setMessage("无法判定要删除的对象");
            return rsp;
        }
        try {
            twitterService.remove(id);
            rsp.setSuccess(true);
            return rsp;
        } catch (Exception e) {
            e.printStackTrace();
            rsp.setSuccess(false);
            rsp.setMessage(e.getMessage());
            return rsp;
        }
    }

    /**********************************************/
    @RequestMapping("/deleteReply")
    @ResponseBody
    public ResponseEntity deleteReply(HttpServletRequest request, HttpServletResponse response, Model model) {
        Long id = RequestUtils.getRequestParameterAsLong(request, "id");
        ResponseEntity rsp = new ResponseEntity();
        if (id == null) {
            rsp.setSuccess(false);
            rsp.setMessage("无法判定要删除的对象");
            return rsp;
        }
        try {
            twitterReplyService.remove(id);
            rsp.setSuccess(true);
            return rsp;
        } catch (Exception e) {
            // TODO: handle exception
            rsp.setSuccess(false);
            rsp.setMessage(e.getMessage());
            return rsp;
        }
    }

    @RequestMapping("/reply")
    @ResponseBody
    public ResponseEntity reply(HttpServletRequest request, HttpServletResponse response, Model model) {
        String content = RequestUtils.getRequestParameterAsString(request, "content");
        Long twitter = RequestUtils.getRequestParameterAsLong(request, "twitter");
        ResponseEntity rsp = new ResponseEntity();
        User user = SecurityUtils.getCurrentUser(request);
        if (user == null) {
            rsp.setSuccess(false);
            rsp.setMessage("请先登录");
            return rsp;
        }
        if (twitter == null) {
            rsp.setSuccess(false);
            rsp.setMessage("无法确认回复对象");
            return rsp;
        }
        if (StringUtils.isBlank(content)) {
            rsp.setSuccess(false);
            rsp.setMessage("请输入要发表的内容");
            return rsp;
        }

        try {
            TwitterReply reply = new TwitterReply();
            reply.setAuthor(user);
            reply.setContent(content);
            reply.setIp(RequestUtils.getRemoteIP(request));
            reply.setTwitter(new Twitter(twitter));
            reply.setCreateTime(new Date());
            reply = twitterReplyService.save(reply);

            rsp.setSuccess(true);
            rsp.setMessage("发表成功");
            rsp.put("twitter", twitter);
            return rsp;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            rsp.setSuccess(false);
            rsp.setMessage("发表内容失败");
            return rsp;
        }
    }

}
